package com.itheima.app.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.domain.mongo.FocusUser;
import com.itheima.domain.mongo.Video;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.FocusUserService;
import com.itheima.service.mongo.VideoService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.CheckForNull;
import java.sql.Struct;
import java.util.ArrayList;
import java.util.List;

@Component
public class VideoManager {

    @DubboReference
    private VideoService videoService;

    @DubboReference
    private UserInfoService userInfoService;

    // 视频分页查询

    // key=  video_userid_pageNum_pageSize
    @Cacheable(value = "tanhua", key = "'video_'+#userId+'_'+#pageNum+'_'+#pageSize")
    public PageBeanVo findVideoVoByPage(Long userId, Integer pageNum, Integer pageSize) {
        System.out.println("查询数据库》。");
        // 1.调用rpc查询视频分页
        PageBeanVo pageBeanVo = videoService.findVideoByPage(userId, pageNum, pageSize);
        // 2.封装vo
        // 2.1 声明voList
        List<VideoVo> voList = new ArrayList<>();
        // 2.2 获取videoList
        List<Video> videoList = (List<Video>) pageBeanVo.getItems();
        // 2.3 遍历
        if (CollectionUtil.isNotEmpty(videoList)) {
            for (Video video : videoList) {
                // 创建vo
                VideoVo vo = new VideoVo();
                vo.setUserInfo(userInfoService.findUserInfoById(video.getUserId())); // 视频发布人信息
                vo.setVideo(video);// 视频详情

                // 是否关注对方
                if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.FOCUS_USER, userId, video.getUserId()))) {
                    vo.setHasFocus(1);
                }

                // 添加到集合
                voList.add(vo);
            }
        }
        // 3.将vo设置到分页对象
        pageBeanVo.setItems(voList);

        // 4.返回分页对象
        return pageBeanVo;
    }

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    // 发布视频
    @CacheEvict(value = "tanhua",key = "'video_'+#userId+'*'")
    public void saveVideo(Long userId, MultipartFile videoThumbnail, MultipartFile videoFile) throws Exception {
        // 1.上传封面
        StorePath storePath1 = client.uploadFile(videoThumbnail.getInputStream(), videoThumbnail.getSize(), FileUtil.extName(videoThumbnail.getOriginalFilename()), null);
        String picUrl = webServer.getWebServerUrl() + storePath1.getFullPath();
        // 2.上传视频
        StorePath storePath2 = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), FileUtil.extName(videoFile.getOriginalFilename()), null);
        String videoUrl = webServer.getWebServerUrl() + storePath2.getFullPath();
        // 3.封装video对象
        Video video = new Video();
        video.setId(ObjectId.get()); // 视频id
        video.setCreated(System.currentTimeMillis()); // 发布时间
        video.setUserId(userId); // 发布人
        video.setText("天苍苍野茫茫，你值的拥有"); // 视频文本
        video.setPicUrl(picUrl); // 视频封面
        video.setVideoUrl(videoUrl); // 视频内容
        // 4.调用rpc保存
        videoService.saveVideo(video);

    }

    @DubboReference
    private FocusUserService focusUserService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 关注
    @CacheEvict(value = "tanhua",key = "'video_'+#userId+'*'")
    public void saveFocusUser(Long userId, Long focusUserId) {
        // 1.封装实体
        FocusUser focusUser = new FocusUser();
        focusUser.setCreated(System.currentTimeMillis());// 关注时间
        focusUser.setUserId(userId); // 你的id
        focusUser.setFocusUserId(focusUserId); // 视频发布人id
        // 2.rpc保存
        focusUserService.saveFocusUser(focusUser);
        // 3.redis存储关注标记
        stringRedisTemplate.opsForValue().set(StrUtil.format(ConstantUtil.FOCUS_USER, userId, focusUserId), "1");
    }

    // 取消关注
    @CacheEvict(value = "tanhua",key = "'video_'+#userId+'*'")
    public void removeFocusUser(Long userId, Long focusUserId) {
        // 1.rpc删除
        focusUserService.removeFocusUser(userId, focusUserId);
        // 2.从reids中删除关注标记
        stringRedisTemplate.delete(StrUtil.format(ConstantUtil.FOCUS_USER, userId, focusUserId));

    }
}
